package com.eshore.norm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.eshore.norm.enumeration.CloudTypeEnum;
import com.eshore.norm.enumeration.CmdbResTypeEnums;
import com.eshore.norm.pojo.constant.Const;
import com.eshore.norm.pojo.dto.NormCluster;
import com.eshore.norm.mapper.NormClusterMapper;
import com.eshore.norm.pojo.po.NormAddressGroupPO;
import com.eshore.norm.pojo.po.NormAvailabilityZonePO;
import com.eshore.norm.pojo.po.NormClusterOverviewPO;
import com.eshore.norm.pojo.vo.SyncCmdbClusterVO;
import com.eshore.norm.service.INormClusterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.conf.Consts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 集群详情 服务实现类
 * </p>
 *
 * @author chenjl
 * @since 2024-01-05
 */
@Slf4j
@Service
public class NormClusterServiceImpl extends ServiceImpl<NormClusterMapper, NormCluster> implements INormClusterService {

    @Override
    public void dataImport(NormAvailabilityZonePO zonePO) {
        log.info("zonePO:{}", zonePO);
        //基础信息（差azId）
        if (zonePO == null || CollectionUtils.isEmpty(zonePO.getContent())) {
            return;
        }
        NormAvailabilityZonePO.ContentDTO contentDTO = zonePO.getContent().get(0);
        if (CollectionUtils.isEmpty(contentDTO.getAvailabilityZoneInfo())) {
            return;
        }
        List<NormAvailabilityZonePO.ContentDTO.AvailabilityZoneInfoDTO> infoDTOS = contentDTO.getAvailabilityZoneInfo();
        //   List<NormAvailabilityZonePO.AvailabilityZoneInfoDTO> infoDTOS = zonePO.getAvailabilityZoneInfo();
        if (CollectionUtils.isNotEmpty(infoDTOS)) {
            //从概览获取azId
            Map<String, String> clusterNameMap = null;
            try {
                String clusterOverviewPO_json="{\"message\":\"请求成功\",\"content\":[{\"cpu\":2460,\"cpu_ratio\":5.24,\"cpu_allocate_ratio\":6.18,\"memory\":6845.08,\"memory_ratio\":4.71,\"memory_allocate_ratio\":6.68,\"vm_count\":9,\"running_count\":7,\"azId\":\"082F1DA2B49E348289F343062EEC3E5F\",\"azName\":\"大数据中心_政务外网区\",\"resourcePoolName\":\"OpenStack_czzwy-xc\",\"storages\":[{\"storage_id\":\"1C3EFE6B88E83569ADCEFF73E7C36559\",\"storage_name\":\"cinder-kvm002@XC_ZWWWAZ_HDDPool01#ZH_XC_ZWWWAZ_HDDPool01\",\"storage_type\":\"未分类\",\"storage\":200.0,\"storage_ratio\":0.07,\"storage_allocate_ratio\":0.02},{\"storage_id\":\"B8431CE0243838EB93F72EE328D5B94F\",\"storage_name\":\"cinder-kvm002@XC_ZWWWAZ_SSDPool01#ZH_XC_ZWWWAZ_SSDPool01\",\"storage_type\":\"大数据中心_政务外网区_SSD\",\"storage\":28.0,\"storage_ratio\":9.55,\"storage_allocate_ratio\":4.74},{\"storage_id\":\"5A09907457B5326EA333F8EBB72007F2\",\"storage_name\":\"cinder-kvm004@XC_ZWWWAZ_SASPool02#ZH_XC_ZWWWAZ_SASPool02\",\"storage_type\":\"未分类\",\"storage\":200.0,\"storage_ratio\":0.03,\"storage_allocate_ratio\":0.0},{\"storage_id\":\"0146CCAA7D613FCEBC32B72637141514\",\"storage_name\":\"cinder-kvm004@XC_ZWWWAZ_SSDPool02#ZH_XC_ZWWWAZ_SSDPool02\",\"storage_type\":\"未分类\",\"storage\":28.0,\"storage_ratio\":0.03,\"storage_allocate_ratio\":0.0}]},{\"cpu\":378,\"cpu_ratio\":10.21,\"cpu_allocate_ratio\":41.8,\"memory\":945.16,\"memory_ratio\":29.58,\"memory_allocate_ratio\":36.95,\"vm_count\":0,\"running_count\":0,\"azId\":\"345FB83181953096ACF5F1BFF7B95D01\",\"azName\":\"manage-az\",\"resourcePoolName\":\"OpenStack_czzwy-xc\",\"storages\":[{\"storage_id\":\"A9A382473EC93AE1B083C15437D5BDDA\",\"storage_name\":\"cinder-kvm001@murano#0\",\"storage_type\":\"manager.fsa.csg\",\"storage\":16.39,\"storage_ratio\":4.72,\"storage_allocate_ratio\":52.25}]},{\"cpu\":672,\"cpu_ratio\":5.59,\"cpu_allocate_ratio\":10.71,\"memory\":1433.98,\"memory_ratio\":11.84,\"memory_allocate_ratio\":10.23,\"vm_count\":7,\"running_count\":6,\"azId\":\"F0EE56E5A817382EB90F4CDA0E9C89FF\",\"azName\":\"大数据中心_互联网区\",\"resourcePoolName\":\"OpenStack_czzwy-xc\",\"storages\":[{\"storage_id\":\"6A0D656A00453ABE801544A9145096DC\",\"storage_name\":\"cinder-kvm003@XC_HLWAZ_HDDPool01#ZH_XC_HLWAZ_HDDPool01\",\"storage_type\":\"未分类\",\"storage\":134.76,\"storage_ratio\":0.03,\"storage_allocate_ratio\":0.0},{\"storage_id\":\"B819EDF30964360181A880A8790DF6A0\",\"storage_name\":\"cinder-kvm003@XC_HLWAZ_SSDPool01#ZH_XC_HLWAZ_SSDPool01\",\"storage_type\":\"大数据中心_互联网区_SSD\",\"storage\":14.0,\"storage_ratio\":4.81,\"storage_allocate_ratio\":3.07},{\"storage_id\":\"3AE81FB00AAB38FAB62E1268806E71CE\",\"storage_name\":\"cinder-kvm005@XC_HLWAZ_SASPool02#ZH_XC_HLWAZ_SASPool02\",\"storage_type\":\"未分类\",\"storage\":134.58,\"storage_ratio\":0.03,\"storage_allocate_ratio\":0.0},{\"storage_id\":\"42AF9F72A1ED3508B0782A07B71E185A\",\"storage_name\":\"cinder-kvm005@XC_HLWAZ_SSDPool02#ZH_XC_HLWAZ_SSDPool02\",\"storage_type\":\"未分类\",\"storage\":14.0,\"storage_ratio\":0.03,\"storage_allocate_ratio\":0.0}]}],\"status\":200,\"total\":3,\"timestamp\":\"2024-01-26T09:11:26.004\"}";
                NormClusterOverviewPO clusterOverviewPO = JSON.parseObject(clusterOverviewPO_json,NormClusterOverviewPO.class);
                log.info("clusterOverviewPO:{}", clusterOverviewPO);

                clusterNameMap = clusterOverviewPO
                        .getContent()
                        .stream()
                        .collect(Collectors.toMap(NormClusterOverviewPO.ContentDTO::getAzName, NormClusterOverviewPO.ContentDTO::getAzId));
                log.info("clusterNameMap{}", clusterNameMap);
            } catch (Exception e) {
                log.info(e.getMessage());
            } finally {
            }
            //实体转换
            List<NormCluster> clusters = handleClusters(Const.CONFIG_ID, infoDTOS, clusterNameMap);
            log.info("clusters:{}", clusters);
            List<String> newIds = clusters.stream().map(NormCluster::getAzId).collect(Collectors.toList());
            List<String> delIds = cleanClusterOldData(Const.CONFIG_ID, newIds);
            getBaseMapper().insertOrUpdate(clusters);
            //TODO 同步到CMDB
            syncCmdbCluster(clusters, delIds, Const.RESOURCE_ID,Const.TENANT_CODE);
            log.info("同步完成，资源池为{}", Const.CONFIG_NAME);
        }
    }


    /**
     * 将规格信息同步到cmdb
     *
     * @param clusters
     * @param deleteStrIds
     */
    private void syncCmdbCluster(List<NormCluster> clusters, List<String> deleteStrIds, Long resourceId, Long tenantCode) {
        log.info("deleteStrIds:{}",deleteStrIds);
        List<SyncCmdbClusterVO> syncInfoList = clusters.stream().map(info -> {
            SyncCmdbClusterVO clusterVO = new SyncCmdbClusterVO();
            //BeanUtils.copyProperties(info, clusterVO,"id");
            clusterVO.setClusterId(info.getId().toString())
                    .setClusterName(info.getZoneName())
                    .setCloudType(CloudTypeEnum.PRIVATE.getType())
                    .setResourceId(resourceId)
                    .setResourceType(CmdbResTypeEnums.NORM)
                    .setClusterId(info.getAzId())
                    .setTenantCode(tenantCode)
                    .setAccountId(info.getConfigId())
                    .setId(IdWorker.getId());
            return clusterVO;
        }).collect(Collectors.toList());
        log.info("syncInfoList:{}",syncInfoList);

//        SyncMessageContent<SyncCmdbClusterVO> messageContent = new SyncMessageContent<>();
//        messageContent.setCloudType(SyncMessageContent.CLOUD_TYPE_NORM_CLOUD);
//        messageContent.setResourceType(SyncMessageContent.RESOURCE_TYPE_SYNC_ClUSTER);
//        messageContent.setAddOrUpdateDatas(syncInfoList);
//        messageContent.setRemoveStrIds(deleteStrIds);
//        rabbitService.defaultDirectSend(SyncMessageContent.QUEUE_NAME, JSONObject.toJSONString(messageContent));

    }

    private List<String> cleanClusterOldData(Long configId, List<String> newIds) {
        //查出原来的旧数据
        List<String> oldClusterIds = lambdaQuery().eq(NormCluster::getConfigId, configId).list().stream().map(NormCluster::getAzId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(oldClusterIds)){
            oldClusterIds.removeAll(newIds);
            if (CollectionUtils.isNotEmpty(oldClusterIds)){
                lambdaUpdate().in(NormCluster::getAzId,oldClusterIds).remove();
                return oldClusterIds;
            }
        }
        return null;
    }

    private List<NormCluster> handleClusters(Long configId,List<NormAvailabilityZonePO.ContentDTO.AvailabilityZoneInfoDTO> infoDTOS,Map<String, String> clusterNameMap){
        List<NormCluster> result = new ArrayList<>();
        infoDTOS.forEach(i -> {
            NormCluster cluster = new NormCluster();
            cluster.setId(IdWorker.getId());
            cluster.setConfigId(configId);
            cluster.setCreateDate(new Date());
            cluster.setUpdateDate(new Date());
            cluster.setZoneName(i.getZoneName());
            cluster.setAvailable(i.getZoneState().getAvailable());
            cluster.setAzId(clusterNameMap.get(i.getZoneName()));
            result.add(cluster);
        });
        return result;
    }

}
